// 通用JavaScript工具函数

// AJAX请求封装
class ApiClient {
    static get baseUrl() {
        return window.AppConfig ? window.AppConfig.getBaseUrl() : '';
    }
    
    // GET请求
    static async get(url, params = {}) {
        const queryString = new URLSearchParams(params).toString();
        const fullUrl = queryString ? `${this.baseUrl}${url}?${queryString}` : `${this.baseUrl}${url}`;
        
        try {
            const response = await fetch(fullUrl, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                },
                credentials: 'same-origin'
            });
            return await this.handleResponse(response);
        } catch (error) {
            console.error('GET请求失败:', error);
            throw error;
        }
    }
    
    // POST请求
    static async post(url, data = {}) {
        try {
            const response = await fetch(`${this.baseUrl}${url}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                credentials: 'same-origin',
                body: JSON.stringify(data)
            });
            return await this.handleResponse(response);
        } catch (error) {
            console.error('POST请求失败:', error);
            throw error;
        }
    }
    
    // PUT请求
    static async put(url, data = {}) {
        try {
            const response = await fetch(`${this.baseUrl}${url}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                },
                credentials: 'same-origin',
                body: JSON.stringify(data)
            });
            return await this.handleResponse(response);
        } catch (error) {
            console.error('PUT请求失败:', error);
            throw error;
        }
    }
    
    // DELETE请求
    static async delete(url) {
        try {
            const response = await fetch(`${this.baseUrl}${url}`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                },
                credentials: 'same-origin'
            });
            return await this.handleResponse(response);
        } catch (error) {
            console.error('DELETE请求失败:', error);
            throw error;
        }
    }
    
    // 处理响应
    static async handleResponse(response) {
        if (!response.ok) {
            const errorData = await response.json().catch(() => ({ message: '请求失败' }));
            throw new Error(errorData.message || `HTTP ${response.status}`);
        }
        
        const contentType = response.headers.get('content-type');
        if (contentType && contentType.includes('application/json')) {
            return await response.json();
        }
        return await response.text();
    }
}

// 消息提示工具
class MessageUtil {
    // 显示成功消息
    static showSuccess(message, duration = 3000) {
        this.showMessage(message, 'success', duration);
    }
    
    // 显示错误消息
    static showError(message, duration = 5000) {
        this.showMessage(message, 'danger', duration);
    }
    
    // 显示警告消息
    static showWarning(message, duration = 4000) {
        this.showMessage(message, 'warning', duration);
    }
    
    // 显示信息消息
    static showInfo(message, duration = 3000) {
        this.showMessage(message, 'info', duration);
    }
    
    // 显示消息的核心方法
    static showMessage(message, type, duration) {
        // 创建消息容器（如果不存在）
        let container = document.getElementById('message-container');
        if (!container) {
            container = document.createElement('div');
            container.id = 'message-container';
            container.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                z-index: 9999;
                max-width: 400px;
            `;
            document.body.appendChild(container);
        }
        
        // 创建消息元素
        const messageEl = document.createElement('div');
        messageEl.className = `alert alert-${type} alert-dismissible fade show`;
        messageEl.style.cssText = `
            margin-bottom: 10px;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
            animation: slideInRight 0.3s ease-out;
        `;
        
        messageEl.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        
        container.appendChild(messageEl);
        
        // 自动移除
        setTimeout(() => {
            if (messageEl.parentNode) {
                messageEl.style.animation = 'slideOutRight 0.3s ease-in';
                setTimeout(() => {
                    if (messageEl.parentNode) {
                        messageEl.remove();
                    }
                }, 300);
            }
        }, duration);
    }
}

// 表单验证工具
class FormValidator {
    // 验证邮箱
    static validateEmail(email) {
        const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return re.test(email);
    }
    
    // 验证手机号
    static validatePhone(phone) {
        const re = /^1[3-9]\d{9}$/;
        return re.test(phone);
    }
    
    // 验证密码强度
    static validatePassword(password) {
        const result = {
            isValid: false,
            strength: 'weak',
            message: ''
        };
        
        if (password.length < 6) {
            result.message = '密码长度至少6位';
            return result;
        }
        
        if (password.length < 8) {
            result.strength = 'weak';
            result.message = '密码强度：弱';
        } else if (password.match(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/)) {
            result.strength = 'strong';
            result.message = '密码强度：强';
        } else if (password.match(/^(?=.*[a-zA-Z])(?=.*\d)/)) {
            result.strength = 'medium';
            result.message = '密码强度：中';
        } else {
            result.strength = 'weak';
            result.message = '密码强度：弱';
        }
        
        result.isValid = true;
        return result;
    }
    
    // 验证用户名
    static validateUsername(username) {
        if (!username || username.length < 3) {
            return { isValid: false, message: '用户名至少3位' };
        }
        if (username.length > 20) {
            return { isValid: false, message: '用户名最多20位' };
        }
        if (!/^[a-zA-Z0-9_]+$/.test(username)) {
            return { isValid: false, message: '用户名只能包含字母、数字和下划线' };
        }
        return { isValid: true, message: '用户名格式正确' };
    }
}

// 工具函数
class Utils {
    // 格式化日期
    static formatDate(date, format = 'YYYY-MM-DD HH:mm:ss') {
        if (!date) return '';
        
        const d = new Date(date);
        const year = d.getFullYear();
        const month = String(d.getMonth() + 1).padStart(2, '0');
        const day = String(d.getDate()).padStart(2, '0');
        const hours = String(d.getHours()).padStart(2, '0');
        const minutes = String(d.getMinutes()).padStart(2, '0');
        const seconds = String(d.getSeconds()).padStart(2, '0');
        
        return format
            .replace('YYYY', year)
            .replace('MM', month)
            .replace('DD', day)
            .replace('HH', hours)
            .replace('mm', minutes)
            .replace('ss', seconds);
    }
    
    // 格式化价格
    static formatPrice(price) {
        if (price === null || price === undefined) return '¥0.00';
        return `¥${parseFloat(price).toFixed(2)}`;
    }
    
    // 生成星级评分HTML
    static generateStars(rating, maxRating = 5) {
        let html = '';
        const fullStars = Math.floor(rating);
        const hasHalfStar = rating % 1 !== 0;
        
        for (let i = 0; i < fullStars; i++) {
            html += '<i class="fas fa-star"></i>';
        }
        
        if (hasHalfStar) {
            html += '<i class="fas fa-star-half-alt"></i>';
        }
        
        const emptyStars = maxRating - Math.ceil(rating);
        for (let i = 0; i < emptyStars; i++) {
            html += '<i class="far fa-star"></i>';
        }
        
        return html;
    }
    
    // 截断文本
    static truncateText(text, maxLength = 100) {
        if (!text || text.length <= maxLength) return text;
        return text.substring(0, maxLength) + '...';
    }
    
    // 防抖函数
    static debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }
    
    // 节流函数
    static throttle(func, limit) {
        let inThrottle;
        return function() {
            const args = arguments;
            const context = this;
            if (!inThrottle) {
                func.apply(context, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    }
    
    // 获取URL参数
    static getUrlParam(name) {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get(name);
    }
    
    // 设置URL参数
    static setUrlParam(name, value) {
        const url = new URL(window.location);
        url.searchParams.set(name, value);
        window.history.pushState({}, '', url);
    }
    
    // 移除URL参数
    static removeUrlParam(name) {
        const url = new URL(window.location);
        url.searchParams.delete(name);
        window.history.pushState({}, '', url);
    }
    
    // 复制到剪贴板
    static async copyToClipboard(text) {
        try {
            await navigator.clipboard.writeText(text);
            MessageUtil.showSuccess('已复制到剪贴板');
        } catch (err) {
            console.error('复制失败:', err);
            MessageUtil.showError('复制失败');
        }
    }
    
    // 下载文件
    static downloadFile(url, filename) {
        const link = document.createElement('a');
        link.href = url;
        link.download = filename;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
    
    // 图片预加载
    static preloadImage(src) {
        return new Promise((resolve, reject) => {
            const img = new Image();
            img.onload = () => resolve(img);
            img.onerror = reject;
            img.src = src;
        });
    }
    
    // 滚动到顶部
    static scrollToTop(duration = 300) {
        const start = window.pageYOffset;
        const startTime = performance.now();
        
        function scroll(currentTime) {
            const elapsed = currentTime - startTime;
            const progress = Math.min(elapsed / duration, 1);
            const easeInOutQuad = progress < 0.5 
                ? 2 * progress * progress 
                : -1 + (4 - 2 * progress) * progress;
            
            window.scrollTo(0, start * (1 - easeInOutQuad));
            
            if (progress < 1) {
                requestAnimationFrame(scroll);
            }
        }
        
        requestAnimationFrame(scroll);
    }
}

// 分页工具
class PaginationUtil {
    static render(containerId, currentPage, totalPages, onPageChange) {
        const container = document.getElementById(containerId);
        if (!container) return;
        
        let html = '<nav><ul class="pagination">';
        
        // 上一页
        if (currentPage > 1) {
            html += `<li class="page-item"><a class="page-link" href="#" data-page="${currentPage - 1}">上一页</a></li>`;
        }
        
        // 页码
        const startPage = Math.max(1, currentPage - 2);
        const endPage = Math.min(totalPages, currentPage + 2);
        
        if (startPage > 1) {
            html += '<li class="page-item"><a class="page-link" href="#" data-page="1">1</a></li>';
            if (startPage > 2) {
                html += '<li class="page-item disabled"><span class="page-link">...</span></li>';
            }
        }
        
        for (let i = startPage; i <= endPage; i++) {
            const activeClass = i === currentPage ? 'active' : '';
            html += `<li class="page-item ${activeClass}"><a class="page-link" href="#" data-page="${i}">${i}</a></li>`;
        }
        
        if (endPage < totalPages) {
            if (endPage < totalPages - 1) {
                html += '<li class="page-item disabled"><span class="page-link">...</span></li>';
            }
            html += `<li class="page-item"><a class="page-link" href="#" data-page="${totalPages}">${totalPages}</a></li>`;
        }
        
        // 下一页
        if (currentPage < totalPages) {
            html += `<li class="page-item"><a class="page-link" href="#" data-page="${currentPage + 1}">下一页</a></li>`;
        }
        
        html += '</ul></nav>';
        container.innerHTML = html;
        
        // 绑定点击事件
        container.querySelectorAll('.page-link[data-page]').forEach(link => {
            link.addEventListener('click', (e) => {
                e.preventDefault();
                const page = parseInt(e.target.dataset.page);
                if (page !== currentPage) {
                    onPageChange(page);
                }
            });
        });
    }
}

// 加载状态管理
class LoadingUtil {
    static show(elementId) {
        const element = document.getElementById(elementId);
        if (element) {
            element.innerHTML = '<div class="text-center"><div class="loading"></div><p class="mt-2">加载中...</p></div>';
        }
    }
    
    static hide(elementId) {
        const element = document.getElementById(elementId);
        if (element) {
            element.innerHTML = '';
        }
    }
    
    static showButton(buttonElement, text = '处理中...') {
        if (buttonElement) {
            buttonElement.disabled = true;
            buttonElement.innerHTML = `<span class="loading"></span> ${text}`;
        }
    }
    
    static hideButton(buttonElement, originalText) {
        if (buttonElement) {
            buttonElement.disabled = false;
            buttonElement.innerHTML = originalText;
        }
    }
}

// 添加CSS动画
const style = document.createElement('style');
style.textContent = `
    @keyframes slideInRight {
        from {
            transform: translateX(100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }
    
    @keyframes slideOutRight {
        from {
            transform: translateX(0);
            opacity: 1;
        }
        to {
            transform: translateX(100%);
            opacity: 0;
        }
    }
`;
document.head.appendChild(style);

// 全局错误处理
window.addEventListener('unhandledrejection', (event) => {
    console.error('未处理的Promise拒绝:', event.reason);
    MessageUtil.showError('操作失败，请稍后重试');
});

// 导出到全局
window.ApiClient = ApiClient;
window.MessageUtil = MessageUtil;
window.FormValidator = FormValidator;
window.Utils = Utils;
window.PaginationUtil = PaginationUtil;
window.LoadingUtil = LoadingUtil;